package com.zqll.gdx.starter.assets;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.I18NBundle;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.zqll.gdx.starter.assets.utils.SkinFonts;

/**
 * 游戏主菜单演示
 * 展示LibGDX Scene2D各种UI组件的使用，包括中文字体支持
 * 使用shade皮肤主题
 */
public class GameMenuDemo extends ApplicationAdapter {
    public static void main(String[] args) {
        new Lwjgl3Application(new GameMenuDemo(), new Lwjgl3ApplicationConfiguration() {{
            setWindowedMode(800, 600);
        }});
    }

    private Stage stage;
    private Skin skin;
    private I18NBundle i18n;

    // UI组件
    private Table mainTable;
    private Label titleLabel;
    private TextButton startButton;
    private TextButton settingsButton;
    private TextButton exitButton;

    // 设置面板组件
    private Window settingsWindow;
    private Slider volumeSlider;
    private CheckBox soundCheckBox;
    private CheckBox musicCheckBox;
    private SelectBox<String> languageSelectBox;
    private TextField playerNameField;
    private ProgressBar loadingBar;
    private List<String> gameList;
    private ScrollPane scrollPane;

    @Override
    public void create() {
        // 初始化StarterAssets
        StarterAssets.init();
        StarterAssets.loadDefaults();

        // 获取资源
        loadSkinWithChineseFonts();
        i18n = StarterAssets.getI18N();

        // 创建舞台
        stage = new Stage(new ScreenViewport());
        Gdx.input.setInputProcessor(stage);

        // 创建UI
        createMainMenu();
        createSettingsWindow();
    }

    /**
     * 加载shade皮肤并配置中文字体支持
     */
    private Skin loadSkinWithChineseFonts() {
        skin = new Skin(Gdx.files.internal("gdx-skins/shade/skin/uiskin.json"));

        // 按 uiskin.json 的字体名称逐项替换，不做统一替换
        BitmapFont titleFont = StarterAssets.font(24);
        BitmapFont buttonFont = StarterAssets.font(18);
        BitmapFont labelFont = StarterAssets.font(16);

        // 替换 JSON 中的资源名：font-title / font-button / font-label
        SkinFonts.replaceFont(skin, "font-title", titleFont, true, true);
        SkinFonts.replaceFont(skin, "font-button", buttonFont, true, true);
        SkinFonts.replaceFont(skin, "font-label", labelFont, true, true);

        return skin;
    }

    // 已采用全局替换字体策略，样式无需手动更新。

    /**
     * 创建主菜单界面
     */
    private void createMainMenu() {
        mainTable = new Table();
        mainTable.setFillParent(true);
        stage.addActor(mainTable);

        // 游戏标题（直接复用 JSON 样式）
        titleLabel = new Label("魔法冒险游戏", skin, "title-plain");

        // 主菜单按钮 - 直接使用默认样式，字体已经被替换
        startButton = new TextButton("开始游戏", skin);
        settingsButton = new TextButton("游戏设置", skin);
        exitButton = new TextButton("退出游戏", skin);

        // 按钮事件
        startButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                showGameStartDialog();
            }
        });

        settingsButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                settingsWindow.setVisible(true);
            }
        });

        exitButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                Gdx.app.exit();
            }
        });

        // 布局主菜单
        mainTable.add(titleLabel).padBottom(50).row();
        mainTable.add(startButton).width(200).height(50).padBottom(20).row();
        mainTable.add(settingsButton).width(200).height(50).padBottom(20).row();
        mainTable.add(exitButton).width(200).height(50).padBottom(20).row();

        // 添加版本信息（使用 optional 样式）
        Label versionLabel = new Label("版本 1.0.0", skin, "optional");

        Table bottomTable = new Table();
        bottomTable.setFillParent(true);
        bottomTable.bottom().right();
        bottomTable.add(versionLabel).pad(20);
        stage.addActor(bottomTable);
    }

    /**
     * 创建设置窗口
     */
    private void createSettingsWindow() {
        settingsWindow = new Window("游戏设置", skin);
        settingsWindow.setSize(400, 500);
        settingsWindow.setPosition(
                (Gdx.graphics.getWidth() - settingsWindow.getWidth()) / 2,
                (Gdx.graphics.getHeight() - settingsWindow.getHeight()) / 2
        );
        settingsWindow.setVisible(false);
        settingsWindow.setModal(true);

        // 音量控制
        Label volumeLabel = new Label("音量控制:", skin);
        volumeSlider = new Slider(0, 100, 1, false, skin);
        volumeSlider.setValue(75);
        Label volumeValueLabel = new Label("75", skin);

        volumeSlider.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                volumeValueLabel.setText(String.valueOf((int) volumeSlider.getValue()));
            }
        });

        // 音效开关
        soundCheckBox = new CheckBox(" 声音效果", skin);
        soundCheckBox.setChecked(true);

        musicCheckBox = new CheckBox(" 背景音乐", skin);
        musicCheckBox.setChecked(true);

        // 语言选择
        Label languageLabel = new Label("语言选择:", skin);
        languageSelectBox = new SelectBox<>(skin);
        languageSelectBox.setItems("简体中文", "English", "日本語");
        languageSelectBox.setSelected("简体中文");

        // 玩家姓名
        Label nameLabel = new Label("玩家姓名:", skin);
        playerNameField = new TextField("勇敢的冒险者", skin);

        // 加载进度条
        Label progressLabel = new Label("加载进度:", skin);
        loadingBar = new ProgressBar(0, 100, 1, false, skin);
        loadingBar.setValue(60);

        // 游戏列表
        Label gameListLabel = new Label("存档列表:", skin);
        gameList = new List<>(skin);
        gameList.setItems("新手村冒险", "魔法森林探索", "龙之巢穴挑战", "最终boss战", "隐藏关卡");
        scrollPane = new ScrollPane(gameList, skin);
        scrollPane.setFadeScrollBars(false);

        // 按钮
        TextButton applyButton = new TextButton("应用", skin);
        TextButton cancelButton = new TextButton("取消", skin);
        TextButton resetButton = new TextButton("重置", skin);

        applyButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                applySettings();
            }
        });

        cancelButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                settingsWindow.setVisible(false);
            }
        });

        resetButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                resetSettings();
            }
        });

        // 布局设置窗口
        Table contentTable = new Table();
        contentTable.pad(20);

        contentTable.add(volumeLabel).left().padBottom(10).row();
        Table volumeTable = new Table();
        volumeTable.add(volumeSlider).width(200).padRight(10);
        volumeTable.add(volumeValueLabel);
        contentTable.add(volumeTable).left().padBottom(20).row();

        contentTable.add(soundCheckBox).left().padBottom(10).row();
        contentTable.add(musicCheckBox).left().padBottom(20).row();

        contentTable.add(languageLabel).left().padBottom(10).row();
        contentTable.add(languageSelectBox).width(200).left().padBottom(20).row();

        contentTable.add(nameLabel).left().padBottom(10).row();
        contentTable.add(playerNameField).width(200).left().padBottom(20).row();

        contentTable.add(progressLabel).left().padBottom(10).row();
        contentTable.add(loadingBar).width(200).left().padBottom(20).row();

        contentTable.add(gameListLabel).left().padBottom(10).row();
        contentTable.add(scrollPane).width(300).height(100).left().padBottom(20).row();

        Table buttonTable = new Table();
        buttonTable.add(applyButton).width(80).padRight(10);
        buttonTable.add(cancelButton).width(80).padRight(10);
        buttonTable.add(resetButton).width(80);
        contentTable.add(buttonTable).padTop(20);

        settingsWindow.add(contentTable);
        stage.addActor(settingsWindow);
    }

    // 移除不再需要的辅助方法

    /**
     * 显示游戏开始对话框
     */
    private void showGameStartDialog() {
        Dialog dialog = new Dialog("确认", skin) {
            @Override
            protected void result(Object object) {
                if ((Boolean) object) {
                    startGame();
                }
            }
        };

        dialog.text("确定要开始新游戏吗？");
        dialog.button("确定", true);
        dialog.button("取消", false);
        dialog.show(stage);
    }

    /**
     * 开始游戏
     */
    private void startGame() {
        // 这里可以添加游戏开始逻辑
        System.out.println("游戏开始！玩家：" + playerNameField.getText());
        System.out.println("选择的存档：" + gameList.getSelected());
    }

    /**
     * 应用设置
     */
    private void applySettings() {
        System.out.println("应用设置:");
        System.out.println("音量: " + (int) volumeSlider.getValue());
        System.out.println("声音效果: " + soundCheckBox.isChecked());
        System.out.println("背景音乐: " + musicCheckBox.isChecked());
        System.out.println("语言: " + languageSelectBox.getSelected());
        System.out.println("玩家姓名: " + playerNameField.getText());

        settingsWindow.setVisible(false);
    }

    /**
     * 重置设置
     */
    private void resetSettings() {
        volumeSlider.setValue(75);
        soundCheckBox.setChecked(true);
        musicCheckBox.setChecked(true);
        languageSelectBox.setSelected("简体中文");
        playerNameField.setText("勇敢的冒险者");
        loadingBar.setValue(0);
    }

    @Override
    public void render() {
        // 清屏
        Gdx.gl.glClearColor(0.1f, 0.1f, 0.2f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // 更新和绘制舞台
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();

        // 模拟加载进度
        if (loadingBar.getValue() < 100) {
            loadingBar.setValue(loadingBar.getValue() + 0.5f);
        }
    }

    @Override
    public void resize(int width, int height) {
        stage.getViewport().update(width, height, true);

        // 重新定位设置窗口
        settingsWindow.setPosition(
                (width - settingsWindow.getWidth()) / 2,
                (height - settingsWindow.getHeight()) / 2
        );
    }

    @Override
    public void dispose() {
        stage.dispose();
        skin.dispose();
        StarterAssets.dispose();
    }
}